package com.erbao.thread.juc;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CaoBaoYin
 * @since 2022/2/26 16:22
 */
public class ReentrantLockTest {

    private ReentrantLock lock = new ReentrantLock();
    // private ReentrantLock lock = new ReentrantLock(true);

    public static void main(String[] args) {
        new ReentrantLockTest().test();
    }

    public void test(){
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1 start");
                lock.lock();
                System.out.println("t1 acquired lock");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
                System.out.println("t1 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        });
        Thread t2 = new Thread(() -> {
            try {
                System.out.println("t2 start");
                lock.lockInterruptibly();
                System.out.println("t2 acquired lock");
                System.out.println("t2 end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        });
        t1.start();
        t2.start();
        try {
            Thread.sleep(2000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();
    }

    public void m () {
        /*boolean locked = false;
        try {
            locked = lock.tryLock(5L, TimeUnit.SECONDS);
            if (locked) {// 获取到锁
                // todo 代码逻辑
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }*/

        try {
            lock.lockInterruptibly();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


}
